from entities import *


def get_user_list() -> dict:
    """
    读取读者列表
    :return:
    """
    with open('./data/users.txt', 'r', encoding='utf8') as f:
        return eval(f.read())


def get_book_list() -> dict:
    """
    读取数目列表
    :return:
    """
    with open('./data/books.txt', 'r', encoding='utf8') as f:
        return eval(f.read())


def get_record_list() -> set:
    """
    读取数目列表
    :return:
    """
    with open('./data/records.txt', 'r', encoding='utf8') as f:
        return eval(f.read()) or set()


def write_user_list(user_list: dict):
    """
    存储用户列表
    :return:
    """
    with open('./data/users.txt', 'w', encoding='utf8') as f:
        f.write(str(user_list))


def write_book_list(book_list: dict):
    """
    存储书的列表
    :param book_list:
    :return:
    """
    with open('./data/books.txt', 'w', encoding='utf8') as f:
        f.write(str(book_list))


def write_record_list(record_list: set):
    """
    借书记录列表
    :param record_list:
    :return:
    """
    with open('./data/records.txt', 'w', encoding='utf8') as f:
        f.write(str(record_list))


def insert_user(user: User):
    """
    插入用户
    :param user:
    :return:
    """
    all_user = get_user_list()
    all_user.update(user.to_dict())
    write_user_list(all_user)


def insert_book(book: Book):
    """
    插入图书到库存
    :param book:
    :return:
    """
    all_book = get_book_list()
    all_book.update(book.to_dict())
    write_book_list(all_book)


def insert_record(record: Record):
    """
    插入借书记录
    :param record:
    :return:
    """
    all_record = get_record_list()
    all_record.add(record.to_tuple())
    write_record_list(all_record)
